﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using cmdb.keede.common;
using cmdb.keede.entity;
using cmdb.keede.service;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;

namespace cmdb.keede.com.Controllers
{
    public class ApplicationController : Controller
    {
        private readonly IApplicationInfoService _appService;
        private readonly IBusinessInfoService _businessService;

        public ApplicationController(IApplicationInfoService appService, IBusinessInfoService businessService)
        {
            _appService = appService;
            _businessService = businessService;
        }

        public async Task<IActionResult> Index()
        {
            var businessInfos = await _businessService.GetAllBusinessInfosAsync();
            ViewBag.businesses = businessInfos.Select(s => new SelectListItem
            {
                Value = s.Id.ToString(),
                Text = s.Name
            });
            return View();
        }

        public async Task<JsonResult> GetApplicationInfoes(int pageIndex, int pageSize)
        {
            var result = await _appService.GetApplicationInfoesAsync(pageIndex, pageSize);
            return new JsonResult(result, new JsonSerializerSettings()
            {
                Converters = new List<JsonConverter>() { new StringEnumConverter() },
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            });
        }

        public async Task<JsonResult> GetApplicationInfoesByBusinessId(int businessId)
        {
            var result = await _appService.GetApplicationInfoesAsync(businessId);
            return new JsonResult(result, new JsonSerializerSettings()
            {
                Converters = new List<JsonConverter>() { new StringEnumConverter() },
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            });
        }

        public async Task<BizResult<ApplicationInfo>> GetApplicationInfo(int id)
        {
            return await _appService.GetApplicationInfoAsync(id);
        }

        public async Task<BizResult<bool>> DeleteApplicationInfo(int id)
        {
            return await _appService.DeleteApplicationInfoAsync(id);
        }

        [HttpPost]
        public async Task<BizResult<bool>> AddOrUpdateAppInfo(ApplicationInfo app)
        {
            return await _appService.AddOrUpdateAppInfo(app);
        }
    }
}